<template>
  <div id="login">
    <div class="login-wrap">
      <ul class="menu-tab">
        <li
          v-for="item in menuTab"
          :key="item.id"
          :class="{ current: item.current }"
          @click="toggleMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>
      <el-form
        ref="loginForm"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="login-form"
        size="medium"
      >
        <el-form-item prop="username" class="item-form">
          <label>邮箱</label>
          <el-input
            v-model="ruleForm.username"
            type="text"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" class="item-form">
          <label>密码</label>
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="password2"
          class="item-form"
          v-show="model === 'register'"
        >
          <label>重复密码</label>
          <el-input
            v-model="ruleForm.password2"
            type="password"
            autocomplete="off"
            minlength="6"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" class="item-form">
          <label>验证码</label>
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input
                v-model="ruleForm.code"
                minlength="6"
                maxlength="6"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <el-button
                type="success"
                @click="getVCode()"
                :disabled="codeBtn.disabled"
                >{{ codeBtn.text }}</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            @click="submitForm()"
            class="login-btn"
            :disabled="submitBtnDisabled"
            >{{ model === "login" ? "登录" : "注册" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import {
  stripscript,
  validEmail,
  validPassword,
  validCode,
} from "@/utils/validate";
import { getCode, register, login } from "@/api/login";
import sha1 from "js-sha1";
import { setToken, setUsername } from "@/utils/app";

export default {
  name: "login",
  setup(props, context) {
    const router = useRouter();
    const store = useStore();

    const loginForm = ref(null);

    // 菜单选项卡
    const menuTab = reactive([
      { txt: "登录", current: true, type: "login" },
      { txt: "注册", current: false, type: "register" },
    ]);

    // 模块值：register为注册，login为登录
    const model = ref("login");
    // 提交按钮不可用状态
    const submitBtnDisabled = ref(true);
    // 获取验证码按钮信息
    const codeBtn = reactive({
      disabled: false,
      text: "获取验证码",
    });

    // 倒计时
    const timer = ref(null);

    // 表单绑定数据
    let ruleForm = reactive({
      username: "1234567@qq.com",
      password: "a123456",
      password2: "a123456",
      code: "",
    });

    // 验证邮箱
    let validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else if (validEmail(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };

    // 验证密码
    let validatePassword = (rule, value, callback) => {
      // 过滤特殊字符
      ruleForm.password = stripscript(value);
      value = ruleForm.password;

      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (validPassword(value)) {
        callback(new Error("密码为6-20位的数字+字母"));
      } else {
        callback();
      }
    };

    // 验证重复密码
    let validatePassword2 = (rule, value, callback) => {
      // 如果模块值是login则直接通过
      if (model.value === "login") {
        callback();
      }
      // 过滤特殊字符
      ruleForm.password2 = stripscript(value);
      value = ruleForm.password2;

      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value != ruleForm.password) {
        callback(new Error("重复密码不正确"));
      } else {
        callback();
      }
    };

    // 验证验证码
    let validateCode = (rule, value, callback) => {
      // 过滤特殊字符
      ruleForm.code = stripscript(value);
      value = ruleForm.code;

      if (value === "") {
        return callback(new Error("请输入验证码"));
      } else if (validCode(value)) {
        callback(new Error("验证码为6位的数字或字母"));
      } else {
        callback();
      }
    };

    // 表单校验数据
    const rules = reactive({
      username: [{ validator: validateEmail, trigger: "blur" }],
      password: [{ validator: validatePassword, trigger: "blur" }],
      password2: [{ validator: validatePassword2, trigger: "blur" }],
      code: [{ validator: validateCode, trigger: "blur" }],
    });

    /**
     * 切换选项卡菜单
     */
    const toggleMenu = (data) => {
      menuTab.forEach((elem) => {
        elem.current = false;
      });
      data.current = true;
      model.value = data.type;

      // 重置表单
      resetForm();
      // 清除定时器
      clearCountDown();
    };

    /**
     * 获取验证码
     */
    const getVCode = () => {
      if (ruleForm.username == "") {
        ElMessage.error("邮箱不能为空");
        return false;
      }
      if (validEmail(ruleForm.username)) {
        ElMessage.error("邮箱格式错误，请重新输入");
        return false;
      }
      updateCodeBtn(true, "发送中");

      let requestData = { username: ruleForm.username, module: model.value };
      getCode(requestData)
        .then((response) => {
          console.log(response.data);
          ElMessage({
            message: response.data.message,
            type: "success",
          });

          // 启用提交按钮
          submitBtnDisabled.value = false;
          // 倒计时
          countDown(60);
        })
        .catch((error) => {
          console.log(error);
        });
    };

    /**
     * 发送验证码计时器
     */
    const countDown = (count) => {
      // 如果断定时器存在则先清除掉
      if (timer.value) {
        clearInterval(timer.value);
      }
      let time = count;
      timer.value = setInterval(() => {
        time--;
        if (time === 0) {
          clearInterval(timer.value);
          updateCodeBtn(false, "再次获取");
        } else {
          codeBtn.text = `倒计时${time}秒`;
        }
      }, 1000);
    };

    /**
     * 清除计时器
     */
    const clearCountDown = () => {
      clearInterval(timer.value);
      updateCodeBtn(false, "获取验证码");
    };

    /**
     * 更新按钮
     */
    const updateCodeBtn = (disabled, text) => {
      codeBtn.disabled = disabled;
      codeBtn.text = text;
    };

    /**
     * 提交表单
     */
    const submitForm = () => {
      loginForm.value.validate((valid) => {
        if (valid) {
          if (model.value === "login") {
            toLogin();
          } else {
            toRegister();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    /**
     * 重置表单
     */
    const resetForm = () => {
      loginForm.value.resetFields();
    };

    /**
     * 注册
     */
    const toRegister = () => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password), // sha1加密
        code: ruleForm.code,
      };
      register(requestData).then((response) => {
        ElMessage({
          message: response.data.message,
          type: "success",
        });

        // 切换到登录页
        toggleMenu(menuTab[0]);
        // 清除定时器
        clearCountDown();
      });
    };

    /**
     * 登录
     */
    const toLogin = () => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
      };
      login(requestData).then((response) => {
        let data = response.data;
        ElMessage({
          message: data.message,
          type: "success",
        });
        store.commit("app/SET_TOKEN", data.data.token);
        store.commit("app/SET_USERNAME", data.data.username);
        setToken(data.data.token);
        setUsername(data.data.username);
        router.push({ name: "Console" });
      });
    };

    // 生命周期
    onMounted(() => {});

    return {
      loginForm,
      menuTab,
      model,
      submitBtnDisabled,
      codeBtn,
      ruleForm,
      rules,
      toggleMenu,
      submitForm,
      getVCode,
    };
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/config.scss";
#login {
  height: 100vh;
  background-color: $mainColor;
}
.login-wrap {
  width: 330px;
  margin: auto;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(0, 0, 0, 0.1);
  }
}
.login-form {
  margin-top: 29px;
  label {
    display: block;
    font-size: 14px;
    color: #fff;
  }
  .item-form {
    margin-bottom: 13px;
  }
  .login-btn {
    display: block;
    width: 100%;
    margin-top: 19px;
  }
}
</style>